<?php

namespace app\data\controller\shop;

use app\common\enum\OrderEnum;
use app\data\model\DataAddresser;
use app\data\model\DataCity;
use app\data\model\DataExpress;
use app\data\model\DataUnilateralism;
use app\data\model\DataUser;
use app\data\model\DataUserAccount;
use app\data\model\ShopOrder;
use app\data\model\ShopOrderBill;
use app\data\model\ShopOrderDetail;
use app\data\model\ShopOrderBack;
use app\data\model\ShopOrderSend;
use app\data\service\OrderService;
use app\data\service\PaymentService;
use app\data\service\UserAdminService;
use expressage\Kd100;
use Logistics\PrintOrder;
use think\admin\Controller;
use think\admin\extend\CodeExtend;
use think\exception\HttpResponseException;

/**
 * 订单数据管理
 * Class Order
 * @package app\data\controller\shop
 */
class Order extends Controller
{
    /**
     * 支付方式
     * @var array
     */
    protected $payments = [];

    /**
     * 控制器初始化
     */
    protected function initialize()
    {
        parent::initialize();
        $this->payments = PaymentService::getTypeAll();
    }

    /**
     * 订单数据管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->title = '订单数据管理';
        // 状态数据统计
        $this->total = ['t0' => 0, 't4' => 0, 't5' => 0, 't6' => 0,'t7' => 0,'ta' => 0];
        foreach (ShopOrder::mk()->field('status,count(1) total')->where(['payment_type'=>0])->whereIn('status','2,3,4,5,6,7')->group('status')->cursor() as $vo) {
            if($vo['status'] == 2 || $vo['status'] == 3){
                $this->total["t0"] = $vo['total'];
            }else{
                $this->total["t{$vo['status']}"] = $vo['total'];
            }
            $this->total["ta"] += $vo['total'];
        }
        // 订单列表查询
        $query = ShopOrder::mQuery();
        $query->like('order_no,trade_no#truck_send_number,username#truck_address_name,phone#truck_address_phone,address#truck_address_content');
        $query->dateBetween('create_at,payment_datetime,reback_date,reback_audit_date');

        // 用户搜索查询
        $db = DataUser::mQuery()->like('phone|username|nickname#user_keys')->db();
        if ($db->getOptions('where')) $query->whereRaw("uuid in {$db->field('id')->buildSql()}");

        // 推荐来源搜索查询
        $db = DataUser::mQuery()->like('phone|username|nickname#from_keys')->db();
        if ($db->getOptions('where')) $query->whereRaw("puid1 in {$db->field('id')->buildSql()}");

        // 列表选项卡
        if (is_numeric($this->type = trim(input('type', 'ta'), 't'))) {
            if($this->type == 0){
                $query->whereIn('status','2,3');
            }else{
                $query->where(['status' => $this->type]);
            }
        }else{
            $query->whereIn('status','2,3,4,5,6,7');
        }
        $query = $query->equal('getbill');
        // 分页排序处理
        $query= $query->where(['payment_type'=>0])->order('id desc');
        if(input('output') == 'json'){
            $query->page();
        }else{
            $lists = $query->page(true, false, false);
        }
        if (empty($lists['list']) === FALSE) {
            foreach ($lists['list'] as &$lv) {
                $lv['amount_total'] = sprintf("%.2f",$lv['amount_total']/100);
                $lv['amount_express'] = sprintf("%.2f",$lv['amount_express']/100);
                $lv['payment_amount'] = sprintf("%.2f",$lv['payment_amount']/100);
                //如果是售后订单  获取售后相关数据
                $lv['back_status'] = 0;
                if($lv['status'] == 7){
                    $detail = ShopOrderBack::mk()->where(['order_no'=>$lv['order_no']])
                        ->group('apply_no')
                        ->order(['create_at'=>'desc'])
                        ->column('goods_name,num as stock_sales,goods_spec,price_selling,goods_cover,status');
                    if(empty($detail) === FALSE){
                        foreach($detail as &$detailv){
                            $lv['back_status'] = $detailv['status'];
                        }
                    }
                }else{
                    $detail = ShopOrderDetail::mk()->where(['order_no'=>$lv['order_no']])->column('goods_name,stock_sales,goods_spec,price_selling,goods_cover');
                }
                if(empty($detail) === FALSE) {
                    foreach ($detail as &$dv) {
                        $dv['price_selling'] = sprintf("%.2f", $dv['price_selling'] / 100);
                    }
                    $lv['items'] = $detail;
                }else{
                    $lv['items'] = [];
                }
                //检测是否开票
                $have_bill = 0;
                if($lv['getbill'] == 1) {
                    $billinfo = ShopOrderBill::mk()->where(['order_no' => $lv['order_no']])->field('status')->find();
                    if (empty($billinfo) === FALSE) {
                        $billinfo = $billinfo->toArray();
                        $have_bill = $billinfo['status'];
                    }
                }
                $lv['have_bill'] = $have_bill;
                //获取直接推荐人
                $lv['parent'] = [];
                $userInfo = DataUser::mk()->where(['id'=>$lv['uuid']])->field("pre_dis_id")->find();
                if(empty($userInfo) === FALSE){
                    $userInfo = $userInfo->toArray();
                    $parents = DataUser::mk()->where(['id'=>$userInfo['pre_dis_id']])->field("headimg,phone,nickname")->find();
                    if(empty($parents) === FALSE){
                        $parents = $parents->toArray();
                        $lv['parent'] = $parents;
                    }
                }
            }
        }
        $this->list = $lists['list'];
        $this->fetch();
    }

    /**
     * 订单列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _index_page_filter(array &$data)
    {
        UserAdminService::buildByUid($data);
        UserAdminService::buildByUid($data, 'puid1', 'from');
        OrderService::buildData($data);
        foreach ($data as &$vo) {
            if (!is_null($vo['payment_type']) and '' != $vo['payment_type']) {
                $vo['payment_name'] = PaymentService::name($vo['payment_type']);
            }
        }
    }
    /**
     * 退货审批
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function rebackaudit(){
        $map = $this->_vali(['order_no.require' => '订单号不能为空！']);
        $order = ShopOrderBack::mk()->where($map)->select();
        if (empty($order)) $this->error('订单查询异常！');
        $order = $order->toArray();
        if($this->request->isGet()){
            $amount = 0;
            $num = 0;
            $status = 0;
            foreach ($order as &$ov){
                $status = $ov['status'];
                $amount += sprintf("%.2f",$ov['price_selling']*$ov['num']/100);
                $num += $ov['num'];
                $ov['price_selling'] = sprintf("%2f",$ov['price_selling']/100);
            }
            $porderinfo = ShopOrder::mk()->where(['order_no'=>$map['order_no']])
                ->field('reback_audit_date,reback_date,reback_remark,status')
                ->find()->toArray();
            $remark = $porderinfo['reback_remark'];
            $reback_audit_date = $porderinfo['reback_audit_date'];
            $reback_date = $porderinfo['reback_date'];
            $this->vo = array(
                'amount'                    => $amount,
                'num'                       => $num,
                'status'                    => $status,
                'remark'                    => $remark,
                'reback_audit_date'         => $reback_audit_date,
                'reback_date'               => $reback_date,
                'lists'                     => $order,
                'order_no'                  => $map['order_no']
            );
            $this->fetch();
        }else{
            $reback_remark = input('reback_remark','');
            $status = input('status',1,'trim,intval');// 1 通过  2  驳回
             $orderInfo = ShopOrder::mk()->where(array(
                    'order_no'  => $map['order_no']
                ))->find();
                if(empty($orderInfo)) $this->error('订单有误！');
            //驳回后 订单状态改为正常
            if($status == 2){
                $orderstatus = $orderInfo['status'];
            }else{
                $orderstatus = 7;
            }
            $opera = [];
            ShopOrderBack::mk()->startTrans();
            $audit_remark = '驳回';
            if($status == 1){
                $audit_remark = '通过';
            }
           sysoplog('退货审核',"订单：".$map['order_no']."，审核退货申请：".$audit_remark);
            //TODO 通过后  返还优惠券 积分等相关
            $opera[] = ShopOrder::mk()->where(array(
                'order_no'  => $map['order_no']
            ))->save(array(
                'status'    => $orderstatus,
                'reback_remark'         => $reback_remark,
                'reback_audit_date'     => \Tools::getDateTimeByTime()
            ));
            $opera[] = ShopOrderBack::mk()->where([ 'order_no'  => $map['order_no']])->save(array(
                'status'    => $status,
                'update_at' => \Tools::getDateTimeByTime()
            ));
            //归还相应商品库存
            $type = 1;
            if($status == 1) {
                $orderInfo = $orderInfo->toArray();
                if($orderInfo['status'] >= OrderEnum::ORDER_STATUS_DELIVERY){
                    $type = 2;
                }
                $opera = OrderService::stock($map['order_no'], $opera, $type);
            }
            if(\Tools::checkArrayResult($opera)){
                ShopOrderBack::mk()->commit();
                $this->success('退货审批成功！');
            }else{
                ShopOrderBack::mk()->rollback();
                $this->error('退货审批失败！');
            }
        }
    }
    /**
     * 查看退货详情
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function rebackdetail(){
        $map = $this->_vali(['order_no.require' => '订单号不能为空！']);
        $order = ShopOrderBack::mk()->where($map)->select()->toArray();
        if (empty($order)) $this->error('订单查询异常！');
        $amount = 0;
        $num = 0;
        $status = 0;
        foreach ($order as &$ov){
            $status = $ov['status'];
            $amount += sprintf("%.2f",$ov['price_selling']*$ov['num']/100);
            $num += $ov['num'];
            $ov['price_selling'] = sprintf("%2f",$ov['price_selling']/100);
        }
        $porderinfo = ShopOrder::mk()->where(['order_no'=>$map['order_no']])->field('reback_audit_date,reback_date,reback_remark')->find()->toArray();
        $remark = $porderinfo['reback_remark'];
        $reback_audit_date = $porderinfo['reback_audit_date'];
        $reback_date = $porderinfo['reback_date'];
        $this->vo = array(
            'amount'                    => $amount,
            'num'                       => $num,
            'status'                    => $status,
            'remark'                    => $remark,
            'reback_audit_date'         => $reback_audit_date,
            'reback_date'               => $reback_date,
            'lists'                     => $order,
            'order_no'                  => $map['order_no']
        );
        $this->fetch();
    }
    /**
     * 查看开票详情
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkbill(){
        $map = $this->_vali(['order_no.require' => '订单号不能为空！']);
        $order = ShopOrder::mk()->where($map)->find()->toArray();
        if (empty($order)) $this->error('订单查询异常！');
        if($this->request->isGet()) {
            $order['payment_amount'] = sprintf("%.2f", $order['payment_amount'] / 100);
            if ($order['getbill'] == 0) {
                $this->error('参数错误！');
            }
            $billinfo = ShopOrderBill::mk()->where(['order_no' => $map['order_no']])->find();
            if(empty($billinfo) === FALSE){
                $billinfo = $billinfo->toArray();
            }else{
                $billinfo = [];
            }
            $this->vo = $billinfo;
            $this->order = $order;
            $this->fetch();
        }else{
            $img = input('img','','trim');
            if(empty($img)) $this->error('发票图片不能为空！');
            $res = ShopOrderBill::mk()->where(['order_no'=>$map['order_no']])->save(array(
                'status'    =>1,
                'img'       =>$img
            ));
            if($res){
                $this->success('开票成功');
            }else{
                $this->error('开票失败！');
            }
        }
    }
    /**
     * 添加编辑快递单号
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function upsendtruck(){
        $map = $this->_vali(['order_no.require' => '订单号不能为空！']);
        $order = ShopOrder::mk()->where($map)->find()->toArray();
        if (empty($order)) $this->error('订单查询异常！');
        if($this->request->isGet()){
            $this->vo = $order;
            $this->fetch();
        }else{
            $map1 = $this->_vali(['trade_no.require' => '快递单号不能为空！']);
            $res = ShopOrder::mk()->where(array(
                'order_no'  => $map['order_no']
            ))->save(array(
                'trade_no'  =>$map1['trade_no'],
                'status'    =>5,
                'trade_send_time'  =>\Tools::getDateTimeByTime()
            ));
            if($res){
                $this->success('订单发货成功！');
            }else{
                $this->error('订单发货失败！');
            }
        }
    }

    /**
     * 面单发货
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function sendMd(){
        $map = $this->_vali(['order_no.require' => '订单号不能为空！']);
        $order = ShopOrder::mk()->where($map)->find();
        if (empty($order)) $this->error('订单查询异常！');
        $order = $order->toArray();
        if($this->request->isPost()){
           $post = $this->request->post();
            // 模板
            $template = DataUnilateralism::getDetail('*',['id'=>$post['template_id']]);
            if(empty($template) === FALSE){
                $express = DataExpress::getDetail('*',['id'=>$template['express']]);
                $template['express_no'] = $express['code100'] ?? '';
                //发件人
                $addresser = DataAddresser::getDetail('*',['id'=>$post['addresser_id']]);
                if(empty($addresser))$this->error('发件人不存在');
                $order['orderGoods'] = ShopOrderDetail::getLists('*',['order_no'=>$order['order_no']]);
                //快递100下单
                $res = PrintOrder::goPrint($order, $template, $addresser);
                 sysoplog('订单发货',json_encode($res));
                if ($res['code'] == 200) {
                    $kuaidinum = $res['data']['kuaidinum'];
                    $kdComOrderNum = $res['data']['kdComOrderNum'];
                    //发货
                    $data['template_id'] = $post['template_id'];
                    $data['order_id'] = $order['id'];
                    $data['shipping_id'] = $template['express'];
                    $data['invoice_no'] = $kuaidinum;
                    $data['kdComOrderNum'] = $kdComOrderNum;
                    $data['send_type'] = 1;
                    $data['image'] = $res['data']['label'];
                    self::deliveryHandle($data,$addresser, session('user.id'));
                    $this->success('面单下单成功，请下载后打印使用');
                } else {
                    $this->error($res['message']);
                }
            }else{
                $this->error('模板不存在');
            }

        }else{
            $express_lists = DataExpress::getLists('*',['del'=>0]);
            $addresser_lists = DataAddresser::getLists('*',['del'=>0]);
            $template_lists = DataUnilateralism::getLists('*',['del'=>0]);
            $this->vo = [
                'id'                => $order['id'],
                'express_lists'       => $express_lists,
                'addresser_lists'       => $addresser_lists,
                'template_lists'    => $template_lists,
            ];
            $this->order_no = $this->request->get('order_no');
            $this->fetch();
        }
    }

    /**
     * 手填单号发货
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handFill(){
        $map = $this->_vali(['order_no.require' => '订单号不能为空！']);
        $order = ShopOrder::mk()->where($map)->find();
        if (empty($order)) $this->error('订单查询异常！');
        $order = $order->toArray();
        if($this->request->isPost()){
           $post = $this->request->post();
            //发件人
            $addresser = DataAddresser::getDetail('*',['id'=>$post['addresser_id']]);
            if(empty($addresser))$this->error('发件人不存在');
           //发货
            $data['template_id'] = 0;
            $data['order_id'] = $order['id'];
            $data['shipping_id'] = $post['express_id'];
            $data['invoice_no'] = $post['kuaidinum'];
            $data['kdComOrderNum'] = 0;
            $data['send_type'] = 1;
            $data['image'] = "";
            self::deliveryHandle($data,$addresser, session('user.id'),1);
            $this->success('发货成功，请及时关注物流动态');
        }else{
            $express_lists = DataExpress::getLists('*',['del'=>0]);
            $addresser_lists = DataAddresser::getLists('*',['del'=>0]);
            $this->vo = [
                'id'                => $order['id'],
                'express_lists'       => $express_lists,
                'addresser_lists'       => $addresser_lists
            ];
            $this->order_no = $this->request->get('order_no');
            $this->fetch();
        }
    }
    /**
     * 取消面单
     * @return void
     */
    public function cancelMd(){
        $map = $this->_vali(['order_no.require' => '订单号不能为空！']);
        $order = ShopOrder::mk()->where($map)->find();
        if (empty($order)) $this->error('订单查询异常！');
        $order = $order->toArray();
        if($this->request->isPost()){
           $post = $this->request->post();
            // 模板
            $sendinfo = ShopOrderSend::mk()->where($map)->find();
            if (empty($sendinfo)) $this->error('发货单查询异常！');
            $sendinfo = $sendinfo->toArray();
            $template = DataUnilateralism::getDetail('*',['id'=>$sendinfo['template_id']]);
            if(empty($template) === FALSE){
                $express = DataExpress::getDetail('*',['id'=>$template['express']]);
                $template['express_no'] = $express['code100'] ?? '';
                //快递取消面单
                $sendinfo['reason'] = $post['reason'];
                $res = PrintOrder::eorderapi($sendinfo, $template);
                 sysoplog('面单取消',json_encode($res));
                if ($res['code'] == 200) {
                    //更新订单状态为未发货
                    ShopOrder::mk()->update(array(
                        'status'    => 4
                    ),array(
                        'id'  =>$order['id']
                    ))->save();
                    ShopOrderSend::mk()->where(array(
                        'id'    => $sendinfo['id']
                    ))->delete();
                    $this->success('面单取消成功');
                } else {
                    $this->error($res['message']);
                }
            }else{
                $this->error('模板不存在');
            }

        }else{
            $this->order_no = $this->request->get('order_no');
            $this->fetch();
        }
    }
        /**
     * @notes 发货操作
     * @param $data
     * @param $admin_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author suny
     * @date 2021/7/14 10:24 上午
     */
    public static function deliveryHandle($data, $addresser,$admin_id,$is_hand = 0)
    {

        $order_id = $data['order_id'];
        $order = ShopOrder::mk()->where(['id' => $order_id], ['order_goods'])->find()->toArray();

        if ($order['status'] >= OrderEnum::ORDER_STATUS_GOODS) {
            return true;
        }
        $shipping = DataExpress::getDetail('*',['id'=>$data['shipping_id']]);
        if(empty($shipping)) {
            return false;
        }
        //添加发货单
        $delivery_data = [
            'order_no' => $order['order_no'],
            'uuid' => $order['uuid'],
            'address_name' => $order['username'],
            'address_phone' => $order['phone'],
            'address_province' => $order['province']??'',
            'address_city' => $order['city']??'',
            'address_area' => $order['district']??'',
            'address_content' => $order['address'],
            'send_number' => $data['invoice_no'],
            'template_id' => $data['template_id'],
            'kdComOrderNum' => $data['kdComOrderNum'],
            'company_code' => $shipping['code100'],//快递公司
            'company_name' => $shipping['name'],//快递公司
            'send_id'     => $addresser['id'],
            'admin_id' => $admin_id,
            'create_at' => \Tools::getDateTimeByTime(),
            'send_datetime' => \Tools::getDateTimeByTime()
        ];
        $delivery_id = ShopOrderSend::mk()->insertGetId($delivery_data);
        $orderData = array(
            'express_image'     => $data['image']??'',
            'update_at'         => \Tools::getDateTimeByTime(),
            'trade_send_time'   => \Tools::getDateTimeByTime(),
            'trade_no'          => $data['invoice_no'],
            'delivery_id'       => $delivery_id,
            'is_hand_fill'       => $is_hand,
            'status'     => OrderEnum::ORDER_STATUS_GOODS
        );
        //上报小程序发货
        self::upload_shipping($order,$data,$shipping);
        return ShopOrder::update($orderData,['id'=>$order_id]);
    }

        //上报小程序发货
    public static function upload_shipping($order,$data,$shipping){
        $appid = sysconf('wx_appid');
        $secret = sysconf('wx_secret');
        $object = new \Wxchat($appid,$secret);
        $accessToken = $object->getaccesstoken();
        $orderDetail = $order['payment_remark'];
        $order_detail = json_decode($orderDetail,true);
        $order_key = array(
            'order_number_type'=>2,
            'transaction_id'=>$order_detail['transaction_id'],
            'mchid'=>$order_detail['mch_id'],
            'out_trade_no'=>$order_detail['out_trade_no']
        );
        $res = array(
            'order_key'=>$order_key,
            'logistics_type'=>1,
            'delivery_mode'=>'UNIFIED_DELIVERY',
            'shipping_list'=>array(
                'tracking_no'=>$data['invoice_no'],
                'express_company'=>$shipping['code100'],
                'item_desc'=>'图书',
                'contact'=>array(
                    'receiver_contact'=>$order['phone'].','.$order['username']
                )
            ),
            'upload_time'=>date('Y-m-d H:i:s',time()),
            'payer'=>array(
                'openid'=>$order_detail['openid']
            )
        );
        $url = 'https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token='.$accessToken;
        \Tools::curl($url,'POST',$res);
    }
    /**
     * 面单下载
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function downloadMd(){
        //
        $map = $this->_vali(['order_no.require' => '订单号不能为空！',]);
        $order = ShopOrder::mk()->where($map)->find()->toArray();
        if (empty($order)) $this->error('订单查询异常！');
        if(empty($order['express_image'])) $this->error('订单面单查询异常！');
        $respath = \Tools::downfile($order['express_image']);
        $filename = substr(strrchr($respath, '/'), 1);//文件名称
        ShopOrder::update(['is_download'=>1,'update_at'=>\Tools::getDateTimeByTime()],['order_no'=>$order['order_no']]);
        //执行浏览器下载
        \Tools::download_file($respath, $filename);
        if (file_exists($respath)) {
            unlink($respath);
        }
    }

    /**
     * 订单跟踪
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderTrace(){
        $map = $this->_vali(['order_no.require' => '订单号不能为空！']);
        $order = ShopOrder::mk()->where($map)->find();
        if (empty($order)) $this->error('订单查询异常！');
        $order = $order->toArray();
        $data = [];
        //初始化数据
        $order_tips = '已下单';
        $order_traces = [];
        $traces = [];//物流轨迹
        $shipment = [//发货
            'title' => '已发货',
            'tips' => '',
            'time' => '',
        ];
        $finish = [//交易完成
            'title' => '交易完成',
            'tips' => '',
            'time' => '',
        ];
        $data['trade_no'] = $order['trade_no'];
        $orderSend = ShopOrderSend::getDetail('address_code,address_name,address_phone,address_content,
            company_code,send_number,send_id',
            array(
                'order_no'  => $order['order_no']
            ));
        $addresser = DataAddresser::getDetail('*',['id'=>$orderSend['send_id']]);
        $send_address = '';
        if(empty($addresser) === FALSE){
            $province = DataCity::getProvince($addresser['province_id']);
            $city = DataCity::getCity($addresser['city_id']);
            $send_address .= $province;
            $send_address .= $city;
        }
        $data['mobile'] = $orderSend['address_phone'];
        $address = explode('市',$orderSend['address_content']);
        $data['to_address'] = $address[0].'市';
        $data['from_address'] = $send_address;
        $data['express_no'] = $orderSend['company_code'];
        $key = sysconf('kd100_appkey');// 客户授权key
        $kd100_customer = sysconf('kd100_customer');// 查询公司编号
        $expressage = (new Kd100($kd100_customer, $key));
        $expressage->logistics($data);
//        $res_data = PrintOrder::synQuery($data);
        $order_delivery = ShopOrderSend::getDetail('company_name',['order_no'=>$order['order_no']]);
        $traces = $expressage->logisticsFormat();
        //获取不到物流轨迹时
        if ($traces == false) {
            $error = $expressage->getError();
            $error = json_decode($error,true);
            if($error['result'] == false){
                $traces[] = [$error['message']];
            }
        } else {
            foreach ($traces as $itemKey => $item) {
                if($itemKey == '')
                $traces[$itemKey] = array_values(array_unique($item));
            }
        }
        //待收货
            if ($order['status'] == 5) {
                $shipment['tips'] = '商品已出库';
                $shipment['time'] = $order['trade_send_time'];
            }
            //确认收货
            if ($order['status'] == 6) {
                $order_tips = '交易完成';
                $finish['tips'] = '订单交易完成';
                $finish['time'] = $order['update_at'];
            }
            //数据合并
            $order_traces = [
                'order' => [
                    'tips' => $order_tips,
                    'count' => $order['number_goods'],
                    'invoice_no' => $order['trade_no'],
                    'shipping_name' => empty($order_delivery['company_name']) ? '-' : $order_delivery['company_name'],
                ],
                'take' => [
                    'contacts' => $order['username'],
                    'mobile' => $order['phone'],
                    'address' => $order['address'],
                ],
                'finish' => $finish,
                'delivery' => [
                    'title' => '运输中',
                    'traces' => $traces
                ],
                'shipment' => $shipment,
                'buy' => [
                    'title' => '已下单',
                    'tips' => '订单提交成功',
                    'time' => $order['payment_datetime']
                ],
            ];
            $this->order_traces = $order_traces;
            $this->fetch();
    }
    /**
     * 取消未支付的订单
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cancel()
    {
        $map = $this->_vali(['order_no.require' => '订单号不能为空！',]);
        $order = ShopOrder::mk()->where($map)->find()->toArray();
        if (empty($order)) $this->error('订单查询异常！');
        if (!in_array($order['status'], [1, 2, 3])) $this->error('订单不能取消！');
        try {
            $opera = [];
            ShopOrder::mk()->startTrans();
            $opera[] = ShopOrder::mk()->update([
                'status'          => 0,
                'cancel_status'   => 1,
                'cancel_remark'   => '后台取消未支付的订单',
                'cancel_datetime' => date('Y-m-d H:i:s'),
            ],$map);
            $opera = OrderService::stock($order['order_no'],$opera,1);
            //如果订单有佣金抵扣  归还佣金
            if ($order['payment_balance'] > 0){
                $opera[] = DataUserAccount::mk()->where(['uuid'=>$order['uuid']])->inc('avail_amount',$order['payment_balance']);
                $opera[] = DataUserAccount::mk()->where(['uuid'=>$order['uuid']])->dec('freeze_amount',$order['payment_balance']);
            }
            //TODO 归还优惠券
            //TODO 归还积分
            sysoplog('取消订单', '管理员：'.session('user.username').'取消订单：'.$order['order_no']);
            if (\Tools::checkArrayResult($opera)) {
                ShopOrder::mk()->commit();
                $this->success('取消未支付的订单成功！');
            } else {
                ShopOrder::mk()->rollBack();
                $this->error('取消支付的订单失败！');
            }
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }
    }
}
